import { reqLogin, reqGetProfile, reqGetBaseInfo } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
// import { Promise } from 'core-js'

const state = {
  token: getToken() || '',
  userInfo: {} // token字符串
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  // 删除token
  removeToken(state) {
    state.token = null
    // 清除vuex token的同时, 同步到本地cookies中移出
    removeToken()
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    const res = await reqLogin(data)
    const newToken = res.data
    context.commit('setToken', newToken)
    return res
  },
  // login(context, data) {
  //   return new Promise((resolve, reject) => {
  //     reqLogin(data).then(res => {
  //       const newToken = res.data
  //       context.commit('setToken', newToken)
  //       resolve(res)
  //     }).catch((err) => {
  //       console.log('请求失败')
  //       reject(err)
  //     })
  //   })
  // },
  // 获取用户资料的action
  // 获取用户资料的action
  async getUserInfo(context) {
    const { data: data1 } = await reqGetProfile()
    const { data: data2 } = await reqGetBaseInfo(data1.userId) // 包含头像的资料
    console.log(data1, data2)
    const resultObj = {
      ...data1,
      ...data2
    }
    context.commit('setUserInfo', resultObj)

    return resultObj
  },
  // 退出的action
  logout(context) {
    // 删除token
    context.commit('removeToken')
    // 删除用户资料
    context.commit('removeUserInfo')
  }
}
const getters = {}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
